﻿using System;
using System.Collections.Generic;
using System.Linq;

using EPiServer.Core;
using EPiServer.Data.Dynamic;

namespace EPiServer.Labs.MobilePack.Core
{
    [EPiServerDataStore(AutomaticallyRemapStore = true, AutomaticallyCreateStore = true)]
    public class RedirectionRule : IDynamicData
    {
        #region Singleton

        private static RedirectionRule instance;

        public static RedirectionRule Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RedirectionRule();
                }

                return instance;
            }
        }

        #endregion


        public Guid SourcePage { get; set; }

        public string VisitorGroup { get; set; }

        public Guid DestinationPage { get; set; }

        public Data.Identity Id { get; set; }

        public string LanguageId { get; set; } 

        private DynamicDataStore Store
        {
             get
             {
                 return typeof(RedirectionRule).GetStore();
             }
        }

        public List<RedirectionRule> LoadForPage(PageData page)
        {
            return Store.Items<RedirectionRule>().Where(r => page.PageGuid == r.SourcePage).ToList();
        }

        public void DeleteRule(Data.Identity r)
        {
            Store.Delete(r);
        }

        public void UpdateRules(PageData page, string Group, PageReference Destination, string languageId)
        {
            RedirectionRule rule = Store.Items<RedirectionRule>().Where(r => page.PageGuid == r.SourcePage && r.VisitorGroup == Group).FirstOrDefault();
            
            if (rule == null)
            {
                rule = new RedirectionRule() { Id = Data.Identity.NewIdentity(), SourcePage = page.PageGuid, VisitorGroup = Group };
            }

            rule.LanguageId = languageId;

            rule.DestinationPage = DataFactory.Instance.GetPage(Destination).PageGuid;
            Store.Save(rule);
        }
    }
}
